package com.xqb.listen.manager.media.utils

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.media.MediaMetadataRetriever
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import android.util.Log
import android.webkit.MimeTypeMap
import java.util.Formatter
import java.util.Locale

/**
 * @author Ling
 * @date :2024/12/12 17:58
 */
object FinderUtil {
    const val SORT_DESC = MediaStore.MediaColumns.DATE_ADDED + " DESC"

    fun isBuildQ() : Boolean{
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q
    }

    fun isBuildR() : Boolean{
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.R
    }

    fun getAlbumProjection() : Array<String>{
        return if (isBuildQ()) AULBUM_PROJECTION else AULBUM_ALL_PROJECTION
    }

    val MEDIA_PROJECTION by lazy {
        arrayOf(
            MediaStore.Files.FileColumns.DATA,
            MediaStore.Files.FileColumns.SIZE,
            MediaStore.Files.FileColumns.WIDTH,
            MediaStore.Files.FileColumns.HEIGHT,
            MediaStore.Files.FileColumns.ARTIST,
            MediaStore.Files.FileColumns.MIME_TYPE,
            MediaStore.Files.FileColumns.DATE_ADDED,
            MediaStore.Files.FileColumns.DISPLAY_NAME,
            "duration",
            "bucket_id",
        )
    }

    val AULBUM_PROJECTION by lazy {
        arrayOf(
            MediaStore.Files.FileColumns.DATA,
            MediaStore.Files.FileColumns.SIZE,
            MediaStore.Files.FileColumns.MIME_TYPE,
            MediaStore.Files.FileColumns.DATE_ADDED,
            "duration",
            "bucket_id",
            "bucket_display_name"
        )
    }

    val AULBUM_ALL_PROJECTION by lazy {
        arrayOf(
            MediaStore.Files.FileColumns.DATA,
            MediaStore.Files.FileColumns.SIZE,
            MediaStore.Files.FileColumns.MIME_TYPE,
            MediaStore.Files.FileColumns.DATE_ADDED,
            "duration",
            "bucket_id",
            "bucket_display_name",
            "COUNT(*) AS count"
        )
    }

    val PPT by lazy { MimeTypeMap.getSingleton().getMimeTypeFromExtension("ppt") }
    val PPTX by lazy { MimeTypeMap.getSingleton().getMimeTypeFromExtension("pptx") }
    val PDF by lazy { MimeTypeMap.getSingleton().getMimeTypeFromExtension("pdf") }
    val XLS by lazy { MimeTypeMap.getSingleton().getMimeTypeFromExtension("xls") }
    val XLSX by lazy { MimeTypeMap.getSingleton().getMimeTypeFromExtension("xlsx") }
    val DOC by lazy { MimeTypeMap.getSingleton().getMimeTypeFromExtension("doc") }
    val DOCX by lazy { MimeTypeMap.getSingleton().getMimeTypeFromExtension("docx") }
    val CSV by lazy { MimeTypeMap.getSingleton().getMimeTypeFromExtension("csv") }
    val TXT by lazy { MimeTypeMap.getSingleton().getMimeTypeFromExtension("txt") }

    /**
     * 如果数据库没有数据，则从路径截取文件名
     */
    fun getNameFromFilepath(str: String): String {
        try {
            val lastSlashIndexOf = str.lastIndexOf("/")
            if(lastSlashIndexOf < 0) return "unknow"
            return str.substring(lastSlashIndexOf + 1)
        } catch (e: StringIndexOutOfBoundsException) {
            e.printStackTrace()
            return "unknow"
        }
    }

    fun isPPT(mimeType : String) : Boolean{
        return mimeType == PPT || mimeType == PPTX
    }

    fun isEXCEL(mimeType : String) : Boolean{
        return mimeType == XLS || mimeType == XLSX
    }

    fun isWORD(mimeType : String) : Boolean{
        return mimeType == DOC || mimeType == DOCX
    }

    fun isTXT(mimeType : String) : Boolean{
        return mimeType == TXT
    }

    fun isCSV(mimeType : String) : Boolean{
        return mimeType == CSV
    }

    fun isPDF(mimeType : String) : Boolean{
        return mimeType == PDF
    }

    //毫秒转文本格式的时分秒
    fun formatTime(milliseconds: Long?): String {
        if(milliseconds == null){
            return "00:00"
        }
        if (milliseconds <= 0 || milliseconds >= 24 * 60 * 60 * 1000) {
            return "00:00"
        }
        val totalSeconds = milliseconds / 1000
        val seconds = totalSeconds % 60
        val minutes = (totalSeconds / 60) % 60
        val hours = totalSeconds / 3600
        val stringBuilder = StringBuilder()
        val mFormatter = Formatter(stringBuilder, Locale.getDefault())
        return if (hours > 0) {
            mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString()
        } else {
            mFormatter.format("%02d:%02d", minutes, seconds).toString()
        }
    }

    fun getAudioArtBitmap(context: Context, url : String?) : Bitmap? {
        if(url.isNullOrEmpty()) return null
        try {
            val uri = Uri.parse(url)
            val myRetriever = MediaMetadataRetriever()
            myRetriever.setDataSource(context, uri)
            val artwork = myRetriever.embeddedPicture
            return if (artwork != null) {
                BitmapFactory.decodeByteArray(artwork, 0, artwork.size)
            } else {
                null
            }
        } catch (e: Exception) {
            Log.e("---->", "setArtwork: ${e.message}")
            return null
        }
    }
}